<script setup lang="ts">
import { ref, onMounted, watch, getCurrentInstance, onUnmounted } from 'vue'
import { ElDialog } from 'element-plus'
import 'element-plus/es/components/dialog/style/css';
import { userStore } from '@/store/user'
import { useCoinStore } from '@/store/coin';
import GuideHeader from '@/components/GuideHeader.vue'
import GuideCoin from '@/components/GuideCoin.vue'
import GuideOrder from '@/components/GuideOrder.vue'
import GuideChart from '@/components/GuideChart.vue'
import GuideNewOrder from '@/components/GuideNewOrder.vue'
import GuideSell from '@/components/GuideSell.vue'
import GuideMyOrder from '@/components/GuideMyOrder.vue'
import Header from '@/components/layout/Header.vue'
import Popup from '@/components/common/Popup.vue'
import modalInfo from './modalInfo.vue'

const draggable = ref(false)
const resizable = ref(false)
const bounded = ref(false)
const showModal = ref(false)
const visible = ref(false)
const defaultActiveMainIndicator = ref('')
const defaultActiveSubIndicator = ref('')
const defaultTab = ref('')
interface GridItem {
    x: number
    y: number
    w: number
    h: number
    i: string
    isLogin: boolean
}

const layout = ref<GridItem[]>([])
const chart = ref({})
const order = ref({})
const header = ref({})
const sell = ref({})
const windowSize = ref<'lg' | 'md' | 'sm' | ''>('')  // 允许空字符串
const sizeLayOut = JSON.parse(JSON.stringify(userStore().sizeLayout))
const layoutUpdated = (griditem: GridItem[]) => {
    const data = griditem
    if (windowSize.value) {  // 添加类型检查
        userStore().changeSizeLayout(windowSize.value, data)
    }
}
type LayoutKey = 'lg' | 'md' | 'sm';
watch(() => windowSize.value, (newValue: string, oldValue: string) => {
    const data = JSON.parse(JSON.stringify(sizeLayOut[windowSize.value as LayoutKey]))
    layout.value = data
})
watch(() => userStore().userInfo.token, (newValue: string, oldValue: string) => {

})
onMounted(() => {
    const updateLayout = () => {

        if (window.innerWidth > 1023) {
            draggable.value = false
            resizable.value = false
            windowSize.value = 'lg'
        } else if (window.innerWidth > 639) {
            draggable.value = false
            resizable.value = false
            windowSize.value = 'md'
        } else {
            draggable.value = false
            resizable.value = false
            windowSize.value = 'sm'
        }
    }
    updateLayout()
    setTimeout(() => {
        const dom = document.getElementsByClassName('vgl-item') as HTMLCollectionOf<HTMLElement>
        dom[0].style.zIndex = '10'
    }, 0);
    window.addEventListener('resize', updateLayout)
    return () => window.removeEventListener('resize', updateLayout)
})
const resizedEvent = (i: string, newH: number, newW: number, newHPx: number, newWPx: number) => {
    const domInfo = {
        width: Number(newWPx),
        height: Number(newHPx)
    }
    if (i == '0') {
        header.value = domInfo
    }
    if (i == '3') {
        chart.value = domInfo
    }
    if (i == '2') {
        order.value = domInfo
    }
    if (i == '4') {
        sell.value = domInfo
    }
}
const containerResizedEvent = (i: string, newH: number, newW: number, newHPx: number, newWPx: number) => {
    // console.log('containerResizedEvent', i, newH, newW, newHPx, newWPx);
    const domInfo = {
        width: Number(newWPx),
        height: Number(newHPx)
    }
    if (i == '0') {
        header.value = domInfo
    }
    if (i == '3') {
        chart.value = domInfo
    }
    if (i == '2') {
        order.value = domInfo
    }
    if (i == '4') {
        sell.value = domInfo
    }
}
const resizeEvent = (i: string, newH: number, newW: number, newHPx: number, newWPx: number) => {
    // const domInfo = {
    //     width: Number(newWPx),
    //     height: Number(newHPx)
    // }
    // if (i == '3') {
    //     chart.value = domInfo
    // }
    // if (i == '2') {
    //     order.value = domInfo
    // }

}
const showindicator = (e: string = 'ma', x: string = 'main') => {
    visible.value = true
    defaultTab.value = x
    if (defaultTab.value == 'main') {
        defaultActiveMainIndicator.value = e || 'ma'
        defaultActiveSubIndicator.value = 'vol'

    } else {
        defaultActiveMainIndicator.value = 'ma'
        defaultActiveSubIndicator.value = e || 'vol'
    }
}
const instance = getCurrentInstance()

let currencySocket: any
const currencyId = ref<string>()

const connectCurrency = () => {
    if (currencyId.value) {
        currencySocket.unsubscribe(currencyId.value, '/topic/market')
    }
    currencyId.value = Date.now().toString(36) + Math.floor(Math.random() * 1000).toString(36)
    currencySocket.subscribe(currencyId.value, `/topic/market`, (data: any) => {
        useCoinStore().setSpotKLine(data.currencyPair, data)
    })
}
watch(() => userStore().currencySocket, (val) => {
    if (val) {
        if (instance) {
            currencySocket = instance.appContext.config.globalProperties.$currencySocket
            if (currencySocket.connected) {
                connectCurrency()
            }
        }
    }
}, { immediate: true })

const updateHeight = (height: number) => {
    if (windowSize.value !== 'lg') {
        return
    }
    const num = Math.ceil((height - 25) / 30) + 1
    if (layout.value.find(item => item.i === '4')!.h !== num) {
        const poor = num - layout.value.find(item => item.i === '4')!.h
        layout.value.find(item => item.i === '4')!.h = num
        layout.value.find(item => item.i === '2')!.h += poor
        layout.value.find(item => item.i === '5')!.h += poor
        layout.value.find(item => item.i === '6')!.y += poor
    }
}
onUnmounted(() => {
    if (currencySocket) {
        currencySocket.unsubscribe(currencyId.value, '/topic/market')
    }
})
</script>

<template>
    <div class="bg-[#f5f5f5]   w-screen dark:bg-[#0c0e11]">
        <ElDialog destroy-on-close v-model="visible" width="672px" title="" style="padding: 0;" :show-close="false"
            v-if="windowSize != 'sm'">
            <modalInfo :defaultActiveMainIndicator="defaultActiveMainIndicator"
                :defaultActiveSubIndicator="defaultActiveSubIndicator" :defaultTab="defaultTab"
                @close="visible = false" />
        </ElDialog>
        <Popup v-model="showModal" direction="bottom" height="438px">
            <div>
                <div class="flex items-center justify-between h-[20px] px-[16px] my-[12px]">
                    <div>市场</div>
                    <span class="iconfont icon-guanbi text-[12px] text-[#9C9C9C]" @click="showModal = false"></span>
                </div>
                <div class="h-[394px] overflow-y-auto" v-if="windowSize == 'sm'">
                    <GuideCoin @changeCoin="showModal = false" />
                </div>
            </div>
        </Popup>
        <Header />
        <GridLayout @layout-updated="layoutUpdated" :margin="[5, 5]" :col-num="30" :animation="0" :transition="false"
            v-model:layout="layout" :row-height="25" :is-bounded="bounded">
            <GridItem drag-allow-from=".vue-draggable-handle" :draggable="false" v-for="item in layout" :key="item.i"
                :x="item.x" :y="item.y" :w="item.w" :h="item.h" :i="item.i" @resize="resizeEvent"
                @resized="resizedEvent" @container-resized="containerResizedEvent" :is-resizable="false">
                <div class=" w-full h-full bg-white dark:bg-[#181a21] rounded-md relative ">
                    <div v-if="draggable"
                        class="vue-draggable-handle absolute  w-1/2 right-0 h-[40px] z-[1] cursor-pointer"></div>
                    <GuideHeader @showCoinInfo="showModal = true" v-if="item.i == '0'" :domInfo="header" />
                    <GuideCoin v-else-if="item.i == '1'" />
                    <GuideOrder :domInfo="order" v-else-if="item.i == '2'" />
                    <GuideChart @showindicator="showindicator" :domInfo="chart" v-else-if="item.i == '3'" />
                    <GuideSell @updateHeight="updateHeight" v-else-if="item.i == '4'" :domInfo="sell" />
                    <GuideNewOrder v-else-if="item.i == '5'" />
                    <GuideMyOrder v-else-if="item.i == '6'" />
                </div>
            </GridItem>
        </GridLayout>
    </div>
</template>
<style scoped>
.vgl-layout {
    /* background-color: #f5f5f5; */
    --vgl-placeholder-bg: #fff;
}

.grid-container {
    gap: 5px !important;
}

:deep(.grid-container) {
    gap: 5px !important;

}

:deep(.vgl-item--resizing) {
    opacity: 90%;
}

:deep(.vgl-item--static) {
    background-color: #cce;
}

.text {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    margin: auto;
    font-size: 24px;
    text-align: center;
}

.layout-json {
    padding: 10px;
    margin-top: 10px;
    background-color: #ddd;
    border: 1px solid black;
}

.columns {
    columns: 120px;
}

:deep(.el-dialog__header) {
    padding: 0;
}
</style>